local record_perc = "_huxi_lastperc"

local dontunequip = {"piratepack"} -- 预备，不要自动脱落的装备，新版本应该用不到这个表
local dontuseitem = {"horrorfuel"}              -- 不要作为燃料添加
local value_terror = 12 -- 泰拉装备默认脱落
local value_dreadstone = value_terror / 2   -- 绝望装备物抗2倍
local value_pocketwatch = value_terror -- 警告表自动修复
local value_mulet = value_dreadstone * 5 -- 护符 30%

local setting = GetModConfigData("sw_myunequip")

local function try_unequip(item, times)
    if setting == "not_add" then
        return
    end
    local slot = item.replica.equippable and item.replica.equippable:EquipSlot()
    local equip = GetEquippedItemFrom(slot) == item
    times = times or 0
    local invent = GLOBAL.ThePlayer and GLOBAL.ThePlayer.replica.inventory
    if equip and invent and times<10 then
        invent:ControllerUseItemOnSelfFromInvTile(item)
        GLOBAL.ThePlayer:DoTaskInTime(0.1, function()
           try_unequip(item, times + 1) 
        end)
    elseif (not equip) and times < 10 then
        TIP("自动脱落", "blue", (item.name or slot or "未知装备")..' 脱落')
    elseif equip and times >= 10 then
        TIP("脱落失败", "red", (item.name or slot or "未知装备"))
    end
end
local act = GLOBAL.ACTIONS
local addactions = {
    act.ADDWETFUEL, act.ADDFUEL,
    -- act.FEED,            -- 喂食算了吧，打架呢还喂食
    act.SEW,act.REPAIR_BONE,act.GIVE,
    act.REPAIRCOMMON,act.REPAIR
}
local function try_sew(target, notunequip)
    if setting == "not_sew" then
        return
    end
    local items = GetItemsFromAll()
    local picker = GLOBAL.ThePlayer and GLOBAL.ThePlayer.components.playeractionpicker
    for _, useitem in pairs(items) do
        if useitem ~= target and picker and useitem and not table.contains(dontuseitem, useitem.prefab) then
            local rights = picker:GetUseItemActions(target, useitem, true)
            for _, right in pairs(rights)do
                local action = type(right)=="table" and right.action
                if table.contains(addactions, action) then
                    SendRPCAtoB(GLOBAL.RPC.ControllerUseItemOnItemFromInvTile, action, useitem, target)
                    if not notunequip then
                        TIP("自动脱落", "blue", useitem.name .. " 修复 " .. target.name)
                        GLOBAL.ThePlayer:DoTaskInTime(4, function()
                            local slot = target.replica.equippable and target.replica.equippable:EquipSlot()
                            local equip = GetEquippedItemFrom(slot) == target
                            if equip and GetPerc(target) <= 1 then
                                TIP("修复失败, 自动脱落", "red", (target.name or slot or "未知装备"))
                                try_unequip(target)
                            end
                        end)
                    end
                    return true
                end
            end
        end
    end
end
AddPrefabPostInit('inventoryitem_classified', function(inc)
    inc:DoTaskInTime(0.1, function(inst)
        local item = inst.entity:GetParent()
        if item and item:HasTag("_equippable") then
            item[record_perc] = GetPerc(item)
            inc:ListenForEvent('percentuseddirty', function()
                local nowperc = GetPerc(item)
                local lastperc = item[record_perc]
                if type(lastperc) == "number" and lastperc > nowperc then
                    local slot = item.replica.equippable and item.replica.equippable:EquipSlot()
                    local prefab = item.prefab
                    if GetEquippedItemFrom(slot)==item then -- 正在装备
                        if table.contains(dontunequip, prefab) then
                            return
                        end
                        if item:HasOneOfTags({
                            "needssewing",      -- 可用缝纫包修复的
                            "NIGHTMARE_fueled", -- 可用噩梦燃料修复的
                            "fedbyall",         -- 可用喂食修复的
                            "dreadstone",       -- 绝望装备
                            "repairable_nightmare",-- 科雷，懒人护符和魔光还标签不一样么？！！！
                        }) and (not item:HasOneOfTags({
                            "fossil",           -- 骨甲
                        }))and nowperc ~= 0     -- 耐久能到0的仅尝试修补 
                        then
                            if (prefab == "pocketwatch_weapon" and nowperc <= value_pocketwatch)
                                or (table.contains({"yellowamulet", "orangeamulet"}, prefab) and (nowperc < value_mulet) and (nowperc > 1))
                            then
                                -- 仅修复，不脱落
                                try_sew(item, true)
                            elseif (table.contains({"eyemaskhat", "shieldofterror"}, prefab) and nowperc<=value_terror)
                                or (table.contains({"armordreadstone","dreadstonehat"}, prefab) and nowperc<=value_dreadstone)
                                or nowperc <= 1 then
                                    -- 不能修再脱
                                    if not try_sew(item) then
                                        try_unequip(item)
                                    end
                            end
                        elseif table.contains({"armor_elepheetle", "hat_elepheetle"}, prefab) and nowperc<=value_dreadstone then
                            -- 直接脱
                            try_unequip(item)
                        elseif nowperc <= 1 then
                            -- 能修，但没修好，就脱
                            try_sew(item)
                        end
                    end
                end
                item[record_perc] = nowperc
            end)
        end
    end)
end)
